package com.wangyadong.hobby.metric.histograms;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.MetricRegistry;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/12/1818:20
 * count = 5              次数
 * min = 0                最小值
 * max = 7                最大值
 * mean = 3.52            平均值
 * stddev = 2.43          标准误差率
 * median = 4.00          中间值
 * 75% <= 5.00            搜索结果小5
 * 95% <= 7.00            搜索结果小7
 * 98% <= 7.00              搜索结果小7
 * 99% <= 7.00              搜索结果小7
 * 99.9% <= 7.00             搜索结果小7
 * <p>
 * uniform reservoirs 统一水库方法 Vitter's R 算法
 * Exponentially Decaying Reservoirs
 * Sliding Window Reservoirs
 * Sliding Time Window Reservoirs
 **/
public class HistoGramExample {

    private static final MetricRegistry metricRegistry = new MetricRegistry();
    private static final ConsoleReporter report = ConsoleReporter.forRegistry(metricRegistry).convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS).build();
    private static final Histogram histogram = metricRegistry.histogram("search");

    public static void main(String[] args) {

        report.start(10, TimeUnit.SECONDS);
        while (true) {
            doSearch();
            randomSleep();
        }

    }

    private static void doSearch() {
        //拿到的结果
        histogram.update(ThreadLocalRandom.current().nextInt(10));
    }

    private static void randomSleep() {
        try {
            TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(5));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
